package Poker;

public class Hand {

	private Card[] cards;

	public Hand() {
		cards = new Card[5];
	}

	protected void changeCards(final int hash, final Deck deck) {
		int unhash = hash;
		for (int i = 0; i < 5; i++) {
			if (unhash % 2 == 0) {
				cards[i] = deck.getCard();
			}
			unhash /= 2;
		}
		Card temp;
		for (int i = 4; i > 0; i--) {
			for (int j = 0; j < i; j++) {
				if (cards[j].getSuit() > cards[j + 1].getSuit()) {
					temp = cards[j];
					cards[j] = cards[j + 1];
					cards[j + 1] = temp;
				}
			}
		}
	}

	public Card getCard(final int index) {
		return cards[index];
	}

	public int rank() {

		// color test
		int color = cards[0].getColor();
		for (int i = 1; i < 5; i++) {
			if (color != cards[i].getColor()) {
				color = -1;
				break;
			}
		}

		// street test
		int street = cards[0].getSuit();
		for (int i = 1; i < 5; i++) {
			if (street + i != cards[i].getSuit()) {
				street = -1;
				break;
			}
		}
		if (street >= 0) {
			if (color >= 0) {
				return 1;
			} else {
				return 5;
			}
		}
		if (color >= 0) {
			return 4;
		}
		// counting same suits;
		int count[] = new int[5];
		int coun = 0;
		count[0] = 1;

		for (int i = 1; i < 5; i++) {
			count[i] = 1;
			if (cards[i].getSuit() == cards[i - 1].getSuit()) {
				count[coun]++;
			} else {
				coun++;
			}
		}
		// sorting to simplify
		int temp;
		for (int i = 4; i > 0; i--) {
			for (int j = 0; j < i; j++) {
				if (count[j] < count[j + 1]) {
					temp = count[j];
					count[j] = count[j + 1];
					count[j + 1] = temp;
				}
			}
		}
		if (count[0] == 4) {
			return 2;
		}
		if (count[0] == 3) {
			if (count[1] == 2) {
				return 3;
			} else {
				return 6;
			}
		}
		if (count[0] == 2) {
			if (count[1] == 2) {
				return 7;
			} else {
				return 8;
			}
		}
		return 9;
	}
}
